import numpy as np
from PIL import Image
from matplotlib import pyplot as plt


def contrast_show(images_dict, subplot_size: tuple, mode="gray", wspace=None, hspace=None, font=None):
    """
        对比显示多张图片
        :param images_dict: 图片对象字典
        :param subplot_size: 绘图子图矩阵尺寸
        :param mode:图像颜色模式，默认是灰度图
        :param wspace: 调整画布子图水平间距
        :param hspace: 调整画布子图竖直间距
        :param font:字体属性
        """
    from matplotlib import pyplot as plt
    from matplotlib import font_manager
    font = font_manager.FontProperties(fname=font)
    plt.subplots_adjust(wspace=wspace, hspace=hspace)
    for index, key in enumerate(images_dict, start=1):
        plt.subplot(*subplot_size, index)
        plt.title(key, fontproperties=font)
        plt.imshow(images_dict[key], cmap=mode)
    plt.show()


def histogram(image_objs, subplot_size: tuple, xticks=None, xrotation=None, wspace=None, hspace=None, bins=100,
              font=None):
    from matplotlib import font_manager
    font = font_manager.FontProperties(fname=font)
    plt.subplots_adjust(wspace=wspace, hspace=hspace)
    for index, key in enumerate(image_objs, start=1):
        plt.subplot(*subplot_size, index)
        plt.title(key, fontproperties=font)
        plt.xticks(ticks=xticks, rotation=xrotation)
        plt.xlabel("像素点区间", fontproperties=font)
        plt.ylabel("像素点频数", fontproperties=font)
        plt.hist(x=np.array(image_objs[key].getdata()), bins=bins)
    plt.show()


def stretch_interval(start, stop, img_array):
    pass


if __name__ == '__main__':
    img_path = "../experiment_fig/fractured_spine.tif"
    my_font = "C:/Windows/Fonts/simsun.ttc"
    im = Image.open(img_path)
    gamma_img1 = im.point(lambda pixel: 10 * np.power(pixel, 0.3))
    gamma_img2 = im.point(lambda pixel: 10 * np.power(pixel, 0.5))
    images = {"原始图像": im, "gamma=0.3": gamma_img1,
              "gamma=0.5": gamma_img2}
    histogram(images, (1, 3), wspace=0.8, font=my_font)
    contrast_show(images, (1, 3), wspace=0.4, font=my_font)
